<?php

namespace App\Http\Controllers\Attendance;

use App\Http\Controllers\Controller;
use App\Imports\Attendance\PersonnelAttendanceImport;
use App\Models\Attendance\AttendancePersonnel;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class PersonnelAttendanceController extends Controller
{
    public function getAttendancePersonnelData(Request $request)
    {
        $params = $request->all();
        $month = $params['month'];
        if (is_null($params['month'])) {
            $month = date('Y-m', strtotime(AttendancePersonnel::query()->max('date')));
        }
        $params['endDate'] = date('Y-m-25', strtotime($month));
        $params['startDate'] = date('Y-m-26', strtotime($month.'- 1 month'));

        $data = $this->getAttendanceData($params)->get()->toArray();

        $data = $this->transData($data, $params);

        return response()->formatJson(['data' => $data, 'month' => $month]);
    }

    public function getAttendanceData($params): Builder
    {
        // 这里使用 DB 查询，可以改善性能
        $query = DB::table('akbus_personnel_attendance')
            ->whereBetween('date', [$params['startDate'], $params['endDate']]);

        if (isset($params['name'])) {
            $query->where('name', 'like', '%'.$params['name'].'%');
        }

        return $query;
    }

    public function transData($data, $params)
    {
        $dateList = getListFromDateRange($params['startDate'], $params['endDate']);
        $sheetData = collect($data)->groupBy('sheet_name');

        $columns = array_merge(
            ['name'],
            $dateList,
            ['working_days', 'late_days', 'casual_leave_days', 'vacation_days']);
        $column = [];
        foreach ($columns as $k => $v) {
            $column[] = $v === 'name' || $v === 'working_days' || $v === 'late_days' || $v === 'casual_leave_days' || $v === 'vacation_days' ? [
                'title' => (($v === 'name') ? '姓名' : (($v === 'working_days') ? '出勤' : (($v === 'late_days') ? '迟到' : (($v === 'casual_leave_days') ? '事假' : '休假')))),
                'key'   => $v,
                'align' => $v === 'name' ? 'left' : 'center',
                'width' => $v === 'name' ? 75 : 55,
                'fixed' => $v === 'name' ? 'left' : 'right',
            ] : [
                'title' => date('m-d', strtotime($v)),
                'key'   => $v,
                'align' => 'center',
                'width' => 70,
            ];
        }

        $allData = [];
        foreach ($sheetData as $sheet => $item) {
            $sheetItem = [];
            $personnelData = $item->groupBy('name')->toArray();
            foreach ($personnelData as $name => $person) {
                $status = array_column($person, 'status');
                $countBy = collect($status)->countBy()->all();
                $item = [];
                $item['name'] = $name;
                $item['working_days'] = $countBy['出勤'] ?? '-';
                $item['late_days'] = $countBy['迟到'] ?? '-';
                $item['casual_leave_days'] = $countBy['事假'] ?? '-';
                $item['vacation_days'] = $countBy['休假'] ?? '-';
                foreach ($dateList as $index => $field) {
                    $item[$field] = $status[$index];
                    $item['cellClassName'][$field] = (($status[$index] === '出勤') ? 'cell-green' : (($status[$index] === '休假') ? 'cell-info' : (($status[$index] === '迟到') ? 'cell-danger' : (($status[$index] === '事假') ? 'cell-error' : ''))));
                }
                $sheetItem[] = $item;
            }
            $allData[$sheet]['data'] = $sheetItem;
            $allData[$sheet]['columns'] = $column;
            $allData[$sheet]['label'] = $sheet;
            $allData[$sheet]['value'] = $sheet;
        }

        return $allData;
    }

    /**
     *  导入行政人员数据
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function importPersonnelAttendance(Request $request)
    {
        $urlParse = parse_url($request->input('url'));

        // 获取文件月份
        $path = explode('/', $urlParse['path']);
        $fileName = $path[count($path) - 1];
        $yearIndex = strpos($fileName, '年');
        $year = substr($fileName, $yearIndex - 4, 4);
        $monthIndex = strpos($fileName, '月');
        $month = substr($fileName, $monthIndex - 2, 2);
        if (!is_numeric($month)) {
            $month = $fileName[$monthIndex - 1];
        }
        $yearMonth = date('Y-m', strtotime($year.'-'.$month));
        $endDate = date('Y-m-25', strtotime($yearMonth));
        $startDate = date('Y-m-26', strtotime($yearMonth.'- 1 month'));

        // 读取文件内容
        $import = new PersonnelAttendanceImport();
        Excel::import($import, public_path().$urlParse['path']);
        $fullData = $import->sheetData;

        $allData = [];
        foreach ($fullData as $sheet => $sheetData) {
            // 删除行
            array_shift($sheetData);
            array_shift($sheetData);
            $dateList = getListFromDateRange($startDate, $endDate);
            $fields = array_merge(['index', 'name'], $dateList);
            array_shift($sheetData);
            foreach ($sheetData as $k => $row) {
                if ($row[1] !== null) {
                    $item = [];
                    foreach ($fields as $index => $field) {
                        $item[$field] = $field !== 'index' && $field !== 'name'
                            ? substr(str_replace(' ', '', $row[$index]), 3)
                            : $row[$index];
                    }
                    if ($item['name']) {
                        $item['name'] = str_replace(' ', '', $item['name']);
                    }
                    foreach ($item as $kk => $vv) {
                        if ($kk !== 'index' && $kk !== 'name') {
                            $allData[] = [
                                'name'       => $item['name'],
                                'date'       => $kk,
                                'status'     => $vv,
                                'sheet_name' => $sheet,
                            ];
                        }
                    }
                }
            }
        }
        AttendancePersonnel::query()->insert($allData);

        return response()->formatJson(true, '导入成功');
    }
}
